from PyQt6.QtGui import QFileSystemModel
from PyQt6.QtWidgets import (QPushButton, QVBoxLayout, 
                                    QWidget, QFileDialog, QMessageBox)
from PyQt6.QtCore import Qt, QDir
import os
from logger import logger
from config import ROOT_DIR

class FileSystemPanel(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        logger.info("初始化文件系统面板")
        self.init_ui()
        
    def init_ui(self):
        # 创建布局
        layout = QVBoxLayout(self)
        
        # 添加文件和文件夹的按钮
        self.add_file_btn = QPushButton('添加文件')
        self.add_dir_btn = QPushButton('添加文件夹')
        self.delete_btn = QPushButton('删除')
        
        # 将按钮添加到布局
        layout.addWidget(self.add_file_btn)
        layout.addWidget(self.add_dir_btn)
        layout.addWidget(self.delete_btn)
        
        # 创建文件系统模型
        self.model = QFileSystemModel()
        self.model.setRootPath(ROOT_DIR)
        
        # 创建树视图并设置模型
        self.tree_view = self.parent().file_tree if self.parent() else None
        if self.tree_view:
            self.tree_view.setModel(self.model)
            self.tree_view.setRootIndex(self.model.index(ROOT_DIR))
            # 只显示文件名
            self.tree_view.setHeaderHidden(True)
            for i in range(1, self.model.columnCount()):
                self.tree_view.hideColumn(i)
        
        layout.addWidget(self.tree_view)
        
        # 连接信号和槽
        self.add_file_btn.clicked.connect(self.add_file)
        self.add_dir_btn.clicked.connect(self.add_directory)
        self.delete_btn.clicked.connect(self.delete_selected)
        
    def add_file(self):
        """添加文件到当前目录"""
        logger.info("开始添加文件操作")
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择文件",
            self.get_current_directory(),
            "所有文件 (*.*)"
        )
        if file_path:
            try:
                # 获取当前选中的目录
                current_dir = self.get_current_directory()
                # 复制文件到当前目录
                basename = os.path.basename(file_path)
                destination = os.path.join(current_dir, basename)
                
                if os.path.exists(destination):
                    error_msg = f"文件已存在: {destination}"
                    logger.error(error_msg)
                    QMessageBox.warning(self, "警告", "文件已存在！")
                    return
                    
                with open(file_path, 'rb') as src_file:
                    with open(destination, 'wb') as dst_file:
                        dst_file.write(src_file.read())
                        
                logger.info(f"文件添加成功: {destination}")
                QMessageBox.information(self, "成功", "文件添加成功！")
            except Exception as e:
                error_msg = f"添加文件失败：{str(e)}"
                logger.error(error_msg)
                QMessageBox.critical(self, "错误", error_msg)
    
    def add_directory(self):
        """添加整个目录"""
        logger.info("开始添加目录操作")
        dir_path = QFileDialog.getExistingDirectory(
            self,
            "选择文件夹",
            self.get_current_directory()
        )
        if dir_path:
            try:
                # 获取当前选中的目录
                current_dir = self.get_current_directory()
                # 复制目录到当前目录
                basename = os.path.basename(dir_path)
                destination = os.path.join(current_dir, basename)
                
                if os.path.exists(destination):
                    error_msg = f"文件夹已存在: {destination}"
                    logger.error(error_msg)
                    QMessageBox.warning(self, "警告", "文件夹已存在！")
                    return
                    
                os.makedirs(destination)
                self.copy_directory(dir_path, destination)
                logger.info(f"文件夹添加成功: {destination}")
                QMessageBox.information(self, "成功", "文件夹添加成功！")
            except Exception as e:
                error_msg = f"添加文件夹失败：{str(e)}"
                logger.error(error_msg)
                QMessageBox.critical(self, "错误", error_msg)
    
    def delete_selected(self):
        """删除选中的文件或文件夹"""
        if not self.tree_view:
            logger.error("文件树视图未初始化")
            return
            
        index = self.tree_view.currentIndex()
        if not index.isValid():
            QMessageBox.warning(self, "警告", "请先选择要删除的文件或文件夹！")
            return
            
        file_path = self.model.filePath(index)
        
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除 '{os.path.basename(file_path)}' 吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            try:
                if os.path.isfile(file_path):
                    os.remove(file_path)
                    logger.info(f"文件删除成功: {file_path}")
                else:
                    import shutil
                    shutil.rmtree(file_path)
                    logger.info(f"目录删除成功: {file_path}")
                QMessageBox.information(self, "成功", "删除成功！")
            except Exception as e:
                error_msg = f"删除失败：{str(e)}"
                logger.error(error_msg)
                QMessageBox.critical(self, "错误", error_msg)
    
    def get_current_directory(self):
        """获取当前选中的目录路径"""
        if not self.tree_view:
            return ROOT_DIR
            
        index = self.tree_view.currentIndex()
        if not index.isValid():
            return ROOT_DIR
            
        path = self.model.filePath(index)
        if os.path.isfile(path):
            return os.path.dirname(path)
        return path
    
    def copy_directory(self, src, dst):
        """递归复制目录"""
        import shutil
        for item in os.listdir(src):
            s = os.path.join(src, item)
            d = os.path.join(dst, item)
            if os.path.isfile(s):
                shutil.copy2(s, d)
            else:
                os.makedirs(d, exist_ok=True)
                self.copy_directory(s, d)
